package com.sinodata.bsm.cicp.finder.linux;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 AM 10:20:07   liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class LinuxCPU extends LinuxFinder {

    private static final Logger logger = Logger.getLogger(LinuxCPU.class);
    private static final String CMDSTR = "cat /proc/cpuinfo";

    public static void main(String[] args) {
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        String[] cpuInfo = null;
        List<String[]> list = new ArrayList<String[]>();
        String strLine = null;
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, CMDSTR, 0, 0);
            while ((strLine = reader.readLine()) != null) {
                String[] st = strLine.split(":");
                if (st.length == 2) {
                    String key = st[0].trim();
                    String value = st[1].trim();
                    if (key.equals("processor")) {//现在遇到一个新的cpu数据,表示上一个cpu发现结束,新cpu发现开始
                        /*
                         * 每一个String[]表示一个资源数据，String[]数据定义如下：
                         * 第一个元素：资源的内部标示   [jobid,nodeid]
                         * 第二个元素：资源名称
                         * 第三个元素：资源描述
                         * 第四-第N个参数：返回的属性值
                         */
                        cpuInfo = new String[6];
                        list.add(cpuInfo);
                        cpuInfo[0] = value;
                        cpuInfo[1] = "CPU" + value;
                        cpuInfo[2] = getHostName(ip) + " CPU" + value;
                        cpuInfo[4] = value;
                    } else if (key.equals("model name")) {
                        cpuInfo[5] = value;
                    } else if (key.equals("cpu MHz")) {
                        cpuInfo[3] = value;
                    }
                }
            }
        } catch (IOException e) {
            logger.error("failed to find linux CPU", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close reader", e);
                }
            }
        }
        return list;
    }
}
